package com.example.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Cache;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式（GET、POST）
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static String httpsRequest(String requestUrl, String requestMethod,
                                     String outputStr) {
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

//            URL url = new URL(requestUrl);
            URL url= new URL(null, requestUrl, new sun.net.www.protocol.https.Handler());
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                    .openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            // httpUrlConn.set
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);
            //添加头部
            Object token = CacheUtils.get("myToken");
            if(token != null){
                httpUrlConn.setRequestProperty("Authorization", String.valueOf(token));
            }
            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

        } catch (ConnectException ce) {
            ce.printStackTrace();
            logger.error("Weixin server connection timed out.");
        } catch (Exception e) {
            logger.error("https request error:{}", e);
        }
        return buffer.toString();
    }

    /**
     * 发起https请求并获取结果
     *
     */



    public static String post(String url, Map<String, String> params, String paramStr){
        URL u = null;
        HttpURLConnection con = null;
        StringBuffer sb = new StringBuffer();
        if(params!=null){
            for (Map.Entry<String, String> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            sb.substring(0, sb.length() - 1);
        } else {
            sb.append(paramStr);
        }
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
            StringBuffer buffer = new StringBuffer();
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                String temp;
                while ((temp = br.readLine()) != null) {
                    buffer.append(temp);
                    buffer.append("\n");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
            return buffer.toString();
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return "";
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }
    public static JSONObject httpRequest(String urladdr, String content)
            throws IOException {
        URL url = new URL(urladdr);
        HttpURLConnection httpConnection = (HttpURLConnection) url
                .openConnection();
        httpConnection.setDoOutput(true);
        httpConnection.setDoInput(true);
        httpConnection.setRequestMethod("POST");
        httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        httpConnection.setConnectTimeout(30000);
        httpConnection.setReadTimeout(30000);
        //添加头部
        Object token = CacheUtils.get("myToken");
        if(token != null){
            httpConnection.setRequestProperty("Authorization", String.valueOf(token));
        }
        OutputStream os = httpConnection.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.write(content.toString().getBytes("utf-8"));
        dos.flush();
        dos.close();
        int nResponseCode = httpConnection.getResponseCode();
        if (nResponseCode == 200) {
            DataInputStream dis = new DataInputStream(httpConnection.getInputStream());
            BufferedInputStream bis = new BufferedInputStream(dis);
            byte bRecByte[] = new byte[1025];
            int nByte = -1;
            ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
            nByte = bis.read(bRecByte, 0, 1024);
            while (nByte != -1) {
                baoStream.write(bRecByte, 0, nByte);
                nByte = bis.read(bRecByte, 0, 1024);
            }
            byte abyte[] = baoStream.toByteArray();
            String strTempRecXml = new String(abyte, "utf-8");
            strTempRecXml = strTempRecXml.replaceAll("&lt;", "<");
            strTempRecXml = strTempRecXml.replaceAll("&gt;", ">");
            JSONObject jsonObject = JSONUtil.parseFromXml(strTempRecXml);
            return jsonObject;
        }
        httpConnection.disconnect();
        return null;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static JSONObject sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //添加头部
            Object token = CacheUtils.get("myToken");
            if(token != null){
                connection.setRequestProperty("Authorization", String.valueOf(token));
            }
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject;
    }

    public static boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest"
                .equals(request.getHeader("X-Requested-With").toString()));
    }

//    public static String getVisitUrl(HttpServletRequest request){
//        StringBuffer toUrl = request.getRequestURL();
//
//        String prms = request.getQueryString();
//        if (prms!=null){
//            toUrl.append("?");
//            toUrl.append(prms);
//        }
//        String url = toUrl.toString();
//        logger.info("url:"+url);
//        url = url.replace("http:","https:");
//        logger.info("url:"+url);
//        return url;
//    }

    public static String getUrl(HttpServletRequest request){
        StringBuffer toUrl = request.getRequestURL();

        String prms = request.getQueryString();
        if (prms!=null){
            toUrl.append("?");
            toUrl.append(prms);
        }
        String url = toUrl.toString();
        //url = url.replace("http:","https:");
        logger.info("url:"+url);
        System.out.println("url============================="+url);
        return url;
    }


    public static JSONObject post(String url, Map<String, Object> paramMap) {
        JSONObject ob = new  JSONObject();
        logger.info("request：" + url);

        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            ob.put(entry.getKey(),entry.getValue());
        }
        logger.info("参数" + ob);
        String result = HttpRequest.post(url).header("Content-Type","application/json").body(ob).execute().body();
        //HttpUtil.encode("Content-Type=application/json","UTF-8");
        // String result = HttpUtil.post(url, paramMap);
        JSONObject jsonObj = JSONUtil.parseObj(result);
        logger.info("response:" + result);
        return jsonObj;
    }

    public static JSONObject post(String url,  JSONObject ob) {
        logger.info("request：" + url);
        logger.info("参数:" + ob);
        String result = HttpRequest.post(url).header("Content-Type","application/json").body(ob).execute().body();
        logger.info("response：\n" + result);
        JSONObject jsonObj = JSONUtil.parseObj(result);
        return jsonObj;
    }

    public static JSONObject post(String url, String data) {
        System.out.println("request：" + url);
        System.out.println("参数:" + data);
        String result = HttpRequest.post(url).header("Content-Type","application/json").body(data).execute().body();
        System.out.println("response：\n" + result);
        JSONObject jsonObj = JSONUtil.parseObj(result);
        return jsonObj;
    }

    public static JSONObject postAddHeader(String url, Map<String, Object> paramMap) throws Exception {
        Object token = CacheUtils.get("myToken");
        if(token == null){
            throw new Exception(" token 为空");
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization",String.valueOf(token));
        JSONObject ob = new  JSONObject();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            ob.put(entry.getKey(),entry.getValue());
        }
        String result = HttpRequest.post(url).header("Content-Type","application/json").addHeaders(headers).body(ob).execute().body();
        JSONObject jsonObj = JSONUtil.parseObj(result);
        logger.info("response：\n" + result);
        return jsonObj;
    }

    public static String postReturnString(String url, Map<String, Object> paramMap) {
        JSONObject ob = new  JSONObject();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            ob.put(entry.getKey(),entry.getValue());
        }
        String result = HttpRequest.post(url).header("Content-Type","application/json").body(ob).execute().body();
        return result;
    }



    public static void main(String[] args) {

    }
}
